package com.xlh.openai.service.impl;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.plexpt.chatgpt.entity.chat.Message;
import com.xlh.openai.dao.ChatRecordsDao;
import com.xlh.openai.entity.ChatRecordsEntity;
import com.xlh.openai.service.ChatRecordsService;
import com.xlh.openai.utils.JsonUtils;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.ArrayList;
import java.util.List;

import static com.plexpt.chatgpt.entity.chat.Message.*;


@Service("chatRecordsService")
public class ChatRecordsServiceImpl extends ServiceImpl<ChatRecordsDao, ChatRecordsEntity> implements ChatRecordsService {

    @Override
    public void saveConversation(Integer userId, Message question, Message answers) {

        String questionJson = JsonUtils.toJson(question);
        String answersJson = JsonUtils.toJson(answers);

        ChatRecordsEntity chatRecordsEntity = new ChatRecordsEntity();
        chatRecordsEntity.setUserId(userId).setQuestion(questionJson).setAnswer(answersJson);
        save(chatRecordsEntity);
    }

    @Override
    public List<Message> listMessages(Integer userId) {

        // 获取最后的四条记录
        QueryWrapper<ChatRecordsEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ChatRecordsEntity::getUserId, userId).last(" order by id desc limit 3");
        List<ChatRecordsEntity> messageList = list(queryWrapper);
        List<Message> list = new ArrayList<>();
        if(CollectionUtil.isEmpty(messageList)){
            return list;
        }
        CollectionUtil.reverse(messageList);
        for (int i = 0; i < messageList.size(); i++) {
            ChatRecordsEntity chatRecordsEntity = messageList.get(i);
            Message question = JSONUtil.toBean( chatRecordsEntity.getQuestion(), Message.class ) ;
            Message answer = JSONUtil.toBean( chatRecordsEntity.getAnswer(), Message.class ) ;
            list.add(question);
            list.add(answer);
        }
        return list;
    }

    @Override
    public List<Message> listMessages(Integer userId, String conversationId) {

        // 获取最后的四条记录
        QueryWrapper<ChatRecordsEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ChatRecordsEntity::getUserId, userId)
                .eq(ChatRecordsEntity::getConversationId, conversationId).last(" order by id desc limit 2");
        List<ChatRecordsEntity> messageList = list(queryWrapper);
        List<Message> list = new ArrayList<>();
        if(CollectionUtil.isEmpty(messageList)){
            return list;
        }
        CollectionUtil.reverse(messageList);
        for (int i = 0; i < messageList.size(); i++) {
            ChatRecordsEntity chatRecordsEntity = messageList.get(i);
            Message question = ofSystem(chatRecordsEntity.getQuestion());
            Message answer = builder().build();
            answer.setRole(Role.SYSTEM.getValue());
            answer.setContent(chatRecordsEntity.getAnswer());
            list.add(question);
            list.add(answer);
        }
        return list;
    }

    @Override
    public List<Message> listMessagesTest(Integer userId, String conversationId) {

        // 获取最后的四条记录
        QueryWrapper<ChatRecordsEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ChatRecordsEntity::getUserId, userId)
                .eq(ChatRecordsEntity::getConversationId, conversationId).last(" order by id desc limit 30");
        List<ChatRecordsEntity> messageList = list(queryWrapper);
        List<Message> list = new ArrayList<>();
        if(CollectionUtil.isEmpty(messageList)){
            return list;
        }
        CollectionUtil.reverse(messageList);
        for (int i = 0; i < messageList.size(); i++) {
            ChatRecordsEntity chatRecordsEntity = messageList.get(i);
            Message question = ofSystem(chatRecordsEntity.getQuestion());
            Message answer = builder().build();
            answer.setRole(Role.SYSTEM.getValue());
            answer.setContent(chatRecordsEntity.getAnswer());
            list.add(question);
            list.add(answer);
        }
        return list;
    }

    @Override
    public void saveConversation(Integer userId, String conversationId,
                                 String prompt, String answer, Long tokens) {

        ChatRecordsEntity chatRecordsEntity = new ChatRecordsEntity();
        chatRecordsEntity
                .setUserId(userId)
                .setQuestion(prompt)
                .setAnswer(answer)
                .setTokens(tokens)
                .setConversationId(conversationId);

        save(chatRecordsEntity);
    }
}